package bancosys.tec.persist.hibernate.type;

import java.sql.Blob;
import java.util.Map;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.BlobType;

/**
 * @author lundberg
 */
public class UpdatableBlobType extends BlobType {

    /**
     * During merge, replace the existing (target) value in the entity we are merging to with a new (original) value from the detached
     * entity we are merging. For immutable objects, or null values, it is safe to simply return the first parameter. For mutable objects,
     * it is safe to return a copy of the first parameter. For objects with component values, it might make sense to recursively replace
     * component values.
     * 
     * @param original the value from the detached entity being merged
     * @param target the value in the managed entity
     * @param session session
     * @param owner owner
     * @param copyCache copyCache
     * @return the value to be merged
     */
    @Override
    public Object replace(Object original, Object target, SessionImplementor session, Object owner, Map copyCache) {
        try {
            return Hibernate.createBlob(((Blob) original).getBinaryStream());
        } catch (Exception e) {
            throw new HibernateException("Error copying the blob during the merge", e);
        }
    }
}
